module FormHelper
  def select_layout
    if params["_window"]
      @window = true
      @input = params[:input]
      @campo_id = params[:campo_id]
      @campo_nombre = params[:campo_nombre]
      nil
    else
      "application"
    end
  end
end

class DotechBuilder < ActionView::Helpers::FormBuilder

  def date_field(method, *args)
    date_select(method,*args)
  end

  def link_to_c(*args, &block)
    link_to(*args, &block)
  end

  #Crea un popup que requiere crear un atributo virtual llamado field_nombre
  # para esto se debe implementar un delegate
  #  delegate :nombre, :to => :empresa, :allow_nil => true, :prefix => true
  #  attr_writer :empresa_nombre
  # f.popup_select :empresa_id, :url => empresas_path
  def popup_select_generico(field, args)
    id_num = args[:random] ? rand(20000)  : 1
    field_name = field.to_s.split("_").slice(0..-2).join("_")
    args[:readonly] = true
    args[:columna_id] ||= :id
    args[:columnas] ||= [:nombre]
    args[:title] ||= "Seleccionar un registro"
    args[:link] = "#{field_name}_#{id_num}"
    args[:id_hidden] = "code_#{field_name}_#{id_num}"
    args[:id_nombre] = "nom_#{field_name}_#{id_num}"
    args[:rand] = id_num
    args[:width] ||= '80%'
    args[:height] ||= '80%'
    args[:conditions] ||= {}
    

    url = @template.url_for(:controller => :popup, :action => :buscar, :opciones => args)
    params_color = []
    params_color << "onClosed: function(){ #{args[:on_close]};}" if args[:on_close]
    params_color << "width:'#{args[:width]}'"
    params_color << "height:'#{args[:height]}'"
    params_color = params_color.join(",")

    #Armar HTML
    text = text_field("#{field_name}_nombre", :id => args[:id_nombre], :readonly => true, :super => true)
    hidden = hidden_field(field, :id => args[:id_hidden])
    link = @template.link_to((text+@template.image_tag("buscar.png")), url, :title => args[:title], :id => "colorbox_#{args[:link]}")
    borrar = @template.image_tag("cancel.png", :id => "limpiar_#{args[:id_nombre]}", :title => "Limpiar selecci&oacute;n", :style => "cursor: pointer;")

    #Boton para limpiar
    @template.content_for :jquery do
      "$('#limpiar_#{args[:id_nombre]}').click(function(){
      $('##{args[:id_nombre]}').val('');
      $('##{args[:id_hidden]}').val('');
    });
  $('#colorbox_#{args[:link]}').colorbox({#{params_color}});"
    end

    link+borrar+hidden
  end

  #Crea un popup que requiere crear un atributo virtual llamado field_nombre
  # para esto se debe implementar un delegate
  #  delegate :nombre, :to => :empresa, :allow_nil => true, :prefix => true
  #  attr_writer :empresa_nombre
  # f.popup_select :empresa_id, :url => empresas_path
  def popup_select(field, args)
    id_num = rand(20000)
    field_name = field.to_s.split("_").slice(0..-2).join("_")
    args[:readonly] = true
    args[:id] = "nom_#{field_name}_#{id_num}"
    args[:super] = true
    args[:tabla] ||= "tabla_#{field_name.pluralize}"
    params_color = []
    params_color << "onClosed: function(){ #{args[:on_close]};}" if args[:on_close]
    more_args = args.clone
    more_args[:link] = "#{field_name}_#{id_num}"
    more_args[:id] = "code_#{field_name}_#{id_num}"
    more_args[:name] = "nom_#{field_name}_#{id_num}"
    more_args[:rand] = id_num
    more_args[:cbox] = params_color
    more_args[:cbclass] ||= 'colorbox'

    url_args = Hash.new
    url_args[:campo_id] = more_args[:id]
    url_args[:campo_nombre] = more_args[:name]
    url_args[:_window] = true
    url_args[:conditions] = more_args[:conditions]
    url = args[:url] + ActionController::Routing::Route.new.build_query_string(url_args)

    #Armar HTML
    text = text_field("#{field_name}_nombre", args.reject{|k,v| k == :url})
    hidden = hidden_field(field, :id => "code_#{field_name}_#{id_num}")
    link = @template.link_to((text+@template.image_tag("buscar.png")), url, :title => "Seleccionar", :class => more_args[:cbclass])
    borrar = @template.image_tag("cancel.png", :id => "limpiar_#{field_name}_#{id_num}", :title => "Limpiar selecci&oacute;n", :style => "cursor: pointer;")

    html = ajax_select(field_name.pluralize, more_args)
    link+borrar+hidden +html
  end
  # == Descripción
  # Agrega funcionalidad jqModal a un elemento por su ID para mostrar un grid de seleccion
  # == Parametros
  # *name*:: nombre del controller a  llamar
  # *opts*:: hash con diferentes opciones
  #
  # == Ejemplo de uso
  #  ajax_select "perfiles", :link => "#trigger_perfil", :id => :perfil_id, :name => :perfil_nombre, :url => perfiles_url
  def ajax_select(name, opts)
    html = <<HTML
  <script type="text/javascript">
    $('.#{opts[:cbclass]}').colorbox({#{opts[:cbox]}});
    function guardar(tabla, nombre, campoid)
    {
      var id = $('#' + tabla ).getGridParam('selrow');
      if (id != null) {
        $('#' + nombre).val($('#' + tabla).getCell(id, 0));
        $('#' + campoid).val(id);
      };
      $.colorbox.close();
    };
    $().ready(function() {
      $('#limpiar_#{opts[:link]}').click(function(){
        $('##{opts[:name]}').val('');
        $('##{opts[:id]}').val('');
      });
    });
  </script>
HTML
    html.html_safe
  end
end


# Estilo Uniform
class UniformBuilder < DotechBuilder
  def submit(method, *args)
    @template.content_tag(:div,super,:class => "buttonHolder")
  end
  def legend(text)
    @template.content_tag(:legend, text)
  end
  #Definir estos helpers
  %w(time_select date_select file_field popup_select popup_select_generico select select_date select_day select_month select_year text_field text_area collection_select check_box password_field).each do |nombre|
    define_method(nombre) do |field, *args|
      options = args.last.is_a?(Hash) ? args.pop : {}
      if options[:super]
        super
      else
        label = label(field, options[:label], :class => options[:label_class])
        hint = options[:hint] ? "<p class='formHint'>#{options[:hint]}</p>" : ""
        @template.content_tag(:p,label + super + hint)
      end
    end
  end
end
